/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { GroupType, OperateRequestBody } from './SpStatisticsHttpBean';

export class SpStatisticsHttpUtil {
  static getToday(): string {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    return year + '-' + month + '-' + day;
  }

  static getPreviousDate(numOfDays: number, baseTime?: string): string {
    let date;
    if (baseTime) {
      date = new Date(baseTime);
    } else {
      date = new Date();
    }
    date.setDate(date.getDate() - numOfDays);
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    return year + '-' + month + '-' + day;
  }

  static initStatisticsServerConfig() {}

  static getCorrectTimeByTimeStr(timeDate: string, isEndTime?: boolean): number {
    let date = new Date(timeDate);
    if (isEndTime) {
      return new Date(date.toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1;
    } else {
      return new Date(date.toLocaleDateString()).getTime();
    }
  }

  static getIntervalCodeByTimeStr(startTime: string, endTime: string): number {
    if (startTime === endTime) {
      return GroupType.HOUR;
    } else {
      let startDate = new Date(startTime).getTime();
      let endDate = new Date(endTime).getTime();
      let day = Math.floor(Math.abs(endDate - startDate) / (1000 * 3600 * 24));
      if (day <= 30) {
        return GroupType.DAY;
      } else if (day > 30 && day <= 360) {
        return GroupType.MONTH;
      } else {
        return GroupType.YEAR;
      }
    }
  }

  static getIntervalCodeByTimeStamp(startTime: number, endTime: number) {
    let dayTs = 3600000 * 24;
    if (endTime - startTime <= dayTs) {
      return GroupType.HOUR;
    } else {
      let day = Math.floor(Math.abs(endTime - startTime) / (1000 * 3600 * 24));
      if (day <= 30) {
        return GroupType.DAY;
      } else if (day > 30 && day <= 360) {
        return GroupType.MONTH;
      } else {
        return GroupType.YEAR;
      }
    }
  }

  static getCorrectTimeByTimeStamp(ts: number, isEndTime?: boolean): number {
    if (isEndTime) {
      return ts + 24 * 60 * 60 * 1000 - 1;
    } else {
      return ts;
    }
  }

  static getServerTime(): number {
    let req = new XMLHttpRequest();
    req.open(
      'GET',
      `${document.location.protocol}//${window.location.host.split(':')[0]}:${
        window.location.port
      }/statistics/serverTime`,
      false
    );
    req.send(null);
    if (req.status == 200) {
      let serverTime = req.responseText;
      if (serverTime && serverTime.length > 0) {
        return Number(serverTime);
      }
    }
    return 0;
  }

  static getUserVisitData(requestUrl: string, callBack?: Function, requestBody?: OperateRequestBody) {
    fetch(
      `${document.location.protocol}//${window.location.host.split(':')[0]}:${
        window.location.port
      }/statistics/${requestUrl}`,
      {
        method: 'post',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody),
      }
    )
      .then((resp) => {
        resp.json().then((it) => {
          if (callBack) {
            callBack(it);
          }
        });
      })
      .catch((err) => {});
  }

  static getOrdinaryVisitData(requestUrl: string, requestBody?: any, callBack?: Function) {
    fetch(
      `${document.location.protocol}//${window.location.host.split(':')[0]}:${
        window.location.port
      }/statistics/${requestUrl}`,
      {
        method: 'post',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody),
      }
    )
      .then((resp) => {
        resp.json().then((it) => {
          if (callBack) {
            callBack(it);
          }
        });
      })
      .catch((err) => {});
  }
}
